﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using BusinessRule.Common;
using BusinessRule.Business;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Threading.Tasks;
using System.Configuration;

//Description:热表生产准备定时任务处理类
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2024-09-27
//Rewriter:
//Rewrite Date:

namespace MESScheduledTask
{
    public class RbProductPrepareCheck
    {
        RbApsLimitedCapacityBusiness rbAps = new RbApsLimitedCapacityBusiness();
        public static readonly int maxParallelSync = Convert.ToInt32(ConfigurationManager.AppSettings["maxParallelSync"].ToString());//最大并行任务数

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="taskList"></param>
        public void RunTaskSync(List<string> taskList)
        {
            //获取需要启动的任务
            DataTable dt = CommonHelper.GetNeedExecuteTask(CommonHelper.TaskTypeEnum.生产准备检查_工步);
            List<Task> tl = new List<Task>();
            foreach (DataRow dr2 in dt.Rows)
            {//开始循环定时任务
                var tempDt = dt.Clone();
                tempDt.ImportRow(dr2);
                var dr = tempDt.Rows[0];//此处必须要给局部变量赋值

                if (taskList.Count >= maxParallelSync)
                {
                    LogHelp.WriteLog("当前正在执行的任务数为：" + taskList.Count.ToString() + " 已达到最大并行限制----------------------------------------------------------------------");
                    break;
                }
                if (taskList.Contains(dr["scheduledtaskid"].ToString()))//已在任务中
                    continue;

                taskList.Add(dr["scheduledtaskid"].ToString());//添加到list中

                tl.Add(Task.Factory.StartNew(() =>
                {
                    try
                    {
                        DealRbProductPrepareCheckTask(dr);
                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteError(dr["taskname"].ToString() + "定时计算异常", ex);
                        CommonHelper.WriteTaskLog(dr["ScheduledTaskId"].ToString(), "3", ex.Message + ex.StackTrace, "1");
                        return;
                    }
                    finally
                    {
                        LogHelp.WriteLog("任务：" + dr["taskname"].ToString() + " " + dr["taskdesc"].ToString() + " 执行完毕，移除队列");
                        taskList.Remove(dr["scheduledtaskid"].ToString());
                    }
                }, TaskCreationOptions.LongRunning));

            }
            //本次产生的task，需要等待完毕
            Task.WaitAll(tl.ToArray());
        }

        /// <summary>
        /// 处理单个任务
        /// </summary>
        /// <param name="dr"></param>
        public void DealRbProductPrepareCheckTask(DataRow dr)
        {
            if (dr["type"].ToString() == "自动未执行")
            {
                CommonHelper.WriteTaskLog(dr["ScheduledTaskId"].ToString(), "2", "", "1");//开始执行
            }
            //Dictionary<string, string> dicAttr = CommonHelper.GetTaskAttr(dr["ScheduledTaskId"].ToString());//获取定时任务的属性

            /*获取转工热表分厂的工序转工信息*/
            uMESProcessResult result = rbAps.GetApsProducePrepData(new Dictionary<string, string> { 
                                        { "factoryId", dr["factoryid"].ToString() }, 
                                        { "status", ""},
                                        { "shipStarts", DateTime.Now.ToString("yyyy-MM-dd") },
                                        { "shipStarte", DateTime.Now.AddDays(3).ToString("yyyy-MM-dd")},
                                        { "orgfactory", ""},
                                        { "shipEnds", ""},
                                        { "shipEnde", ""},
                                        { "ContainerName", ""},
                                        { "MfgOrderName", ""}
                                        }, false);
            if (!result.Result)
            {
                LogHelp.WriteLog(string.Format("分厂：热表，任务：{0} 查询生产准备数据报错，原因：{1}", dr["taskname"].ToString(), result.Message));
                CommonHelper.WriteTaskLog(dr["ScheduledTaskId"].ToString(), "4", " 任务执行完毕，查询生产准备数据报错，原因：" + result.Message, "1");
                return;
            }
            /*定义参数*/
            //int scount = 0, ecount = 0;//成功条数，失败条数
            //string msg = string.Empty;//提示消息

            DataTable dtApsShip = result.DBTable;
            LogHelp.WriteLog(string.Format("分厂：热表，任务：{0}开始执行，执行生产准备总数：{1}-------------------------------------------------------------", dr["taskname"].ToString(), dtApsShip.Rows.Count));
            CommonHelper.UpdateTaskLogStartDate(dr["ScheduledTaskId"].ToString()); //更新定时任务日志的开始时间为当前时间
            /*开始执行数据*/
            rbAps.ReviewDetailData(dtApsShip, dr["factoryid"].ToString(), "");

//            for (int i = 0; i < dtApsShip.Rows.Count; i++)
//            {
//                //检查是否提前终止
//                if (DatabaseHelper.GetSingle(string.Format(@"select 1 from ScheduledTaskLogs sl
//                            where sl.scheduledtaskid='{0}' and sl.islatest=1 and sl.taskexeendtime is not null", dr["ScheduledTaskId"].ToString())) != null)
//                {
//                    break;
//                }
//                DataTable dtApsShipNew = dtApsShip.Clone();
//                dtApsShipNew.Rows.Add(dtApsShip.Rows[i].ItemArray);
//                /*执行转工接收*/
//                rbAps.ReviewDetailData(drApsShip);
//                LogHelp.WriteLog(string.Format("分厂：热表，任务：{0} 的第{1}个批次：{2}的转工序：{3}，{4}", dr["taskname"].ToString(), (i + 1).ToString(), drApsShip["containername"].ToString(), drApsShip["workflowstepname"].ToString(), msg));
//            }
            //此任务执行完毕
            CommonHelper.WriteTaskLog(dr["ScheduledTaskId"].ToString(), "4", string.Format(" 任务执行完毕，执行生产准备总数：{0}", dtApsShip.Rows.Count), "1");
            LogHelp.WriteLog(string.Format("分厂：热表，任务：{0} 执行完毕----------------------------------------------------------------------", dr["taskname"].ToString()));
        }
    }
}
